<?php



namespace App\Services\Member\Models;

use App\Models\AdministratorRole;
use App\Services\Business\Models\Group;
use App\Services\Business\Models\Question;
use App\Services\Business\Models\SearchKeywords;
use App\Services\Company\Models\Company;
use App\Services\Order\Models\Coupon;
use App\Services\Order\Models\RedeemCode;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable, HasFactory;

    public const ACTIVE_YES = 1;
    public const ACTIVE_NO = -1;

    public const LOCK_YES = 1;
    public const LOCK_NO = -1;



    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'avatar','uuid','account', 'nick_name', 'password', 'mobile',
        'is_lock', 'is_active', 'role_id',
        'invite_user_id', 'invite_balance', 'invite_user_expired_at',
        'is_password_set', 'is_set_nickname', 'is_set_avatar', 'is_used_promo_code',
        'register_ip', 'register_area', 'last_login_id','work_years','category_id','is_fulltime','last_follow_updated_at','batch_code','register_province','register_city','is_company_administrator','login_company_id'
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 写入到jwt中的数据
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function invitor()
    {
        return $this->belongsTo(__CLASS__, 'invite_user_id');
    }

    /**
     * 平台所属角色.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }


    public function roles()
    {
        return $this->belongsToMany(AdministratorRole::class, 'administrator_role_relation', 'user_id', 'role_id')->withTimestamps();
    }


    /**
     * 头像修饰器.
     *
     * @return \Illuminate\Config\Repository|mixed
     */
    public function getAvatarAttribute($avatar)
    {
        return $avatar ?: url(config('zesow.member.default_avatar'));
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function inviteBalanceWithdrawOrders()
    {
        return $this->hasMany(UserInviteBalanceWithdrawOrder::class, 'user_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function tags()
    {
        return $this->belongsToMany(UserTag::class, 'user_tag_relation', 'user_id', 'tag_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function profile()
    {
        return $this->hasOne(UserProfile::class, 'user_id');
    }


    public function remark()
    {
        return $this->hasOne(UserRemark::class, 'user_id');
    }


//我的关注
    public function followings()
    {
        return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id')
            ->withTimestamps();
    }
//我的粉丝
    public function followers()
    {
        return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id')
            ->withTimestamps();
    }

    //我的关注题目

    public function quizs()
    {
        return $this->belongsToMany(Question::class, 'user_quiz', 'user_id', 'question_id')
            ->withTimestamps();
    }


    public function coupons()
    {
        return $this->belongsToMany(
            Coupon::class,
            'user_coupons',
            'user_id',
            'coupon_id'
        );
    }
    public function redeemCodes()
    {
        return $this->belongsToMany(
            RedeemCode::class,
            'user_redeem_codes',
            'user_id',
            'redeem_code_id'
        );
    }

    public function keywords()
    {
        return $this->hasMany(SearchKeywords::class, 'user_id');
    }



    /**
     *我的所有公司
     * @return BelongsToMany
     */
    public function companies()
    {
        return $this->belongsToMany(Company::class, 'company_administrator_relation','user_id','company_id');
    }



    /**
     * 是否为超级管理员.
     *
     * @return bool
     */
    public function isSuper()
    {
        return $this->roles()->whereSlug(config('zesow.administrator.super_slug'))->exists();
    }

    /**
     * @param $path
     * @param $method
     * @return bool
     */
    public function hasPermission($path, $method)
    {
        $through = false;
        $roles = $this->roles;
        foreach ($roles as $role) {
            // http method
            $permissions = $role->permissions()->where('method', 'like', "%{$method}%")->get();
            if ($permissions->isEmpty()) {
                continue;
            }
            // url
            foreach ($permissions as $permission) {
                if (preg_match("#{$permission->url}$#i", $path) === 1) {
                    $through = true;
                    break;
                }
            }
        }
        return $through;
    }



    /**
     * 当前管理员是否可以删除.
     *
     * @return bool
     */
    public function couldDestroy()
    {
        return $this->roles()->where('slug', config('zesow.administrator.super_slug'))->exists();
    }


    public  function  relatives()
    {
        return $this->belongsToMany(User::class, 'user_relative', 'user_id', 'relative_id')->withTimestamps();
    }

    public function     redpacketer()
    {
        return $this->belongsToMany(User::class, 'user_redpacket', 'receiver_id', 'user_id')->withTimestamps();
    }

    public function largestOrder()
    {
        return $this->hasOne(Activity::class)->latestOfMany();
    }

    public function  addressTags()
    {
        return $this->hasMany(AddressTag::class, 'user_id');
    }



}
